from PyQt5.QtCore import QThread, pyqtSignal, QSettings
from PyQt5.QtWidgets import QMessageBox
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains



from util.Tools import net_is_used
import os
import logging.config
import traceback

setting = QSettings(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),"config\\config.ini"), QSettings.IniFormat)
setting.setIniCodec("UTF-8")
logging.config.fileConfig(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "config\\logging.ini"))
logger = logging.getLogger("infoLogger")


class chrom_drive(QThread):
    '''
    异步自动化
    '''
    SendTxtSnal = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.rs = None

    def inquery_image(self, list1):
        self.rs = list1  # [[],[]]

    def GetAllDrive(self):
        try:
            ret = None
            chrome_options = Options()
            chrome_options.add_experimental_option("debuggerAddress", setting.value("ChromeWebdrive/chromeipAdress"))
            chrome_driver = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), setting.value("ChromeDrive/driverurl"))
            fou = net_is_used(int(setting.value("ChromeWebdrive/chromeport")), setting.value("ChromeWebdrive/chromeip"))
            if fou:
                if os.path.isfile(chrome_driver):
                    self.brower = webdriver.Chrome(chrome_driver, options=chrome_options)
                    return True
                else:
                    # todo 添加chrome下拉内核
                    logging.error("chrome内核exe文件不存在")
                    return False
            else:
                logging.error("浏览器未打开")

        except Exception:
            logging.error(traceback.format_exc())

    def run(self):
        try:
            if self.rs != None:
                if len(self.rs) > 0:
                    self.TxtDate = ""
                    IsTrue = self.GetAllDrive()
                    if IsTrue:
                        for row in self.rs:
                            self.findElementType = str(row[1]) if row[1] else None
                            self.findValue = str(row[2]) if row[2] else None
                            self.opType = str(row[3]) if row[3] else None
                            self.opValue = str(row[4]) if row[4] else None
                            self.opNum = row[5] if row[5] else None
                            self.executeOrder()
                        if self.TxtDate != "":
                            logging.info(self.TxtDate)
                            self.SendTxtSnal.emit(self.TxtDate)
                            self.TxtDate = ""
            self.rs = None
        except Exception as f:
            logging.error(traceback.format_exc())

    def __del__(self):
        self.wait()

    def executeOrder(self):
        '''
        webdrive 自动化
        :return:
        '''
        try:
            dom = None
            # 定位元素
            if self.findElementType == 'NAME':
                dom = self.brower.find_element_by_name(self.findValue)
            elif self.findElementType == 'ID':
                dom = self.brower.find_element_by_id(self.findValue)
            elif self.findElementType == 'XPATH':
                dom = self.brower.find_element_by_xpath(self.findValue)
            elif self.findElementType == 'LINK_TEXT':
                dom = self.brower.find_element_by_link_text(self.findValue)
            elif self.findElementType == 'PARTIAL_LINK_TEXT':
                dom = self.brower.find_element_by_partial_link_text(self.findValue)
            elif self.findElementType == 'TAG_NAME':
                dom = self.brower.find_element_by_tag_name(self.findValue)
            elif self.findElementType == 'CLASS_NAME':
                dom = self.brower.find_element_by_class_name(self.findValue)
            else:
                dom = self.brower.find_element_by_css_selector(self.findValue)
            if int(self.opNum) == 1:
                Action = ActionChains(self.brower)
                if self.opType == 'double_click':
                    Action.double_click(dom).perform()
                if self.opType == 'key_down':
                    Action.key_down(dom).perform()
                if self.opType == 'key_up':
                    Action.key_up(dom).perform()
                if self.opType.upper() == 'CLICK':
                    Action.move_to_element(dom).click().perform()
                if self.opType.upper() == "LEFT_CLICK":
                    Action.click_and_hold(dom).release().perform()
                if self.opType.upper() == "REIGHT_CLICK":
                    Action.context_click(dom).release().perform()
            elif int(self.opNum) == 2:
                if self.findValue != None:
                    # 执行操作
                    if self.opType.upper() == 'SEND_KEY':
                        if self.opValue == 'Keys.SPACE':
                            dom.send_keys(Keys.SPACE)
                        elif self.opValue == 'Keys.TAB':
                            dom.send_keys(Keys.TAB)
                        elif self.opValue == 'Keys.ESPACE':
                            dom.send_keys(Keys.ESCAPE)
                        elif self.opValue == 'Keys.ENTER':
                            dom.send_keys(Keys.ENTER)
                        elif self.opValue == 'Keys.F1':
                            dom.send_keys(Keys.F1)
                        else:
                            dom.clear()
                            dom.send_keys(self.opValue)
                    if self.opType.upper() == 'CLICK':
                        dom.click()
                    if self.opType.upper() == "TEXT":
                        Textret = dom.text
                        self.TxtDate = self.TxtDate + str(Textret)
                    if self.opType.upper() == "GET_ATTRIBUTE":
                        classret = dom.get_attribute(self.opValue)
                        logging.info(classret)
                        self.TxtDate = self.TxtDate + str(classret)
            else:
                if self.opType.upper() == 'IFRAME':
                    if self.findElementType.upper() == 'ID':
                        self.brower.switch_to.frame(self.findValue)
                    elif self.findElementType.upper() == 'NAME':
                        self.brower.switch_to.frame(self.findValue)
                if self.opType.upper() == 'EXIT_IFRAME':
                    self.brower.switch_to.default_content()
                if self.opType.upper() == "WINDOW":
                    ret = self.brower.window_handles
                    self.brower.switch_to.window(ret[int(self.opValue)])
                if self.opType.upper() == 'JS':
                    self.brower.execute_script(self.opValue, dom)
        except Exception:
            logging.error(traceback.format_exc())


